package com.kuaifu.autofare.controller.web.interceptor;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kuaifu.autofare.controller.web.annotation.RegisterRequired;

public class UserHandleInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            RegisterRequired registerRequired = findAnnotation(
                    (HandlerMethod) handler, RegisterRequired.class);
            // 没有声明需要校验openid，appid是否在绑定手机号码
            if (registerRequired == null) {
                // if (StringUtils.isBank(userid)) {
                // UserInfo userInfo = userInfoService.getUserInfoByOpenId(
                // openid, appid);
                // if (userInfo == null) {// 未绑定，则跳转到注册页面
                // request.getRequestDispatcher("/register/page?userid").forward(
                // request, response);
                // return false;
                // }
                // }

            }
        }
        return true;
    }

    private <T extends Annotation> T findAnnotation(HandlerMethod handler,
                                                    Class<T> annotationType) {
        T annotation = handler.getBeanType().getAnnotation(annotationType);
        if (annotation != null)
            return annotation;
        return handler.getMethodAnnotation(annotationType);
    }

}
